/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.manager;

import entity.Message;
import entity.Player;
import java.util.Collection;
import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author antonio
 */

@Stateless
public class MessageManagerBean implements MessageManagerBeanLocal {
    
    @PersistenceContext(unitName = "BrowserGame-ejbPU")
    private EntityManager entityManager;

    @Override
    public void createMessage(String username, String text) {
        Player player = entityManager.find(Player.class, username);
        if(player == null) {
            throw new IllegalArgumentException("Giocatore destinatario non trovato");
        }
        Message message = new Message(1);
        message.setDate(new Date());
        message.setUser(player);
        message.setText(text);
        message.setRead(Boolean.FALSE);
        entityManager.persist(message);
        player.getMessageCollection().add(message);
    }

    @Override
    public void deleteMessage(int id) {
        Message message = entityManager.find(Message.class, id);
        if(message == null) {
            throw new IllegalArgumentException("Messaggio inesistente");
        }
        entityManager.remove(message);
    }

    @Override
    public void markAsRead(int id) {
        Message message = entityManager.find(Message.class, id);
        if(message == null) {
            throw new IllegalArgumentException("Messaggio inesistente");
        }
        message.setRead(Boolean.TRUE);
    }

    @Override
    public Collection<Message> getMessages(String username) {
        Player player = entityManager.find(Player.class, username);
        if(player == null) {
            throw new IllegalArgumentException("Giocatore destinatario non trovato");
        }
        return player.getMessageCollection();
    }

}
